package com.ypj.rpc.transport.socket.server;

import com.ypj.rpc.entity.RpcRequest;
import com.ypj.rpc.entity.RpcResponse;
import com.ypj.rpc.handler.RequestHandler;
import com.ypj.rpc.serializer.CommonSerializer;
import com.ypj.rpc.transport.socket.utils.ObjectReader;
import com.ypj.rpc.transport.socket.utils.ObjectWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 请求处理线程
 */
@Slf4j
public class SocketRequestHandlerThread implements Runnable {

    private Socket socket;
    private RequestHandler requestHandler;
    private CommonSerializer serializer;

    public SocketRequestHandlerThread(Socket socket, RequestHandler requestHandler, CommonSerializer serializer) {
        this.socket = socket;
        this.requestHandler = requestHandler;
        this.serializer = serializer;
    }

    @Override
    public void run() {
        try (OutputStream outputStream=socket.getOutputStream();
             InputStream inputStream=socket.getInputStream()){
            RpcRequest request=(RpcRequest) ObjectReader.readObject(inputStream);
            Object result=requestHandler.handle(request);
            RpcResponse<Object> response=RpcResponse.success(result,request.getRequestId());
            ObjectWriter.writeObject(outputStream,response,serializer);
        } catch (IOException e) {
            log.error("调用或发送时有错误发生："+e.getMessage(),e);
        }
    }

}
